package group.pals.launcher;

import group.pals.mailgate.commons.Lib;
import group.pals.utils.files.FileUtils;
import group.pals.utils.launcher.Launcher;
import group.pals.utils.sys.MessageBox;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Hello world!
 *
 */
public class LauncherLoader implements Launcher {

  public static final boolean Debug = false;

  /**
   * <b>NOTE:</b> do not add arguments to this constructor, because the class loader
   * will only calls this with no arguments!
   */
  public LauncherLoader() {
    //
  }

  private File rootPath = null;

  @Override
  public int setRootPath(File rootPath) {
    this.rootPath = rootPath;
    return 0;
  }

  @Override
  public int update() {
    if (Debug) {
      System.out.printf("%s: update()  :-)\n", getClass().getSimpleName());
    }

    List<File> files = new ArrayList<File>();
    final int newFileCount = FileUtils.enumFiles(rootPath, new NewFileFilter(), files, 100, null, 0);
    if (newFileCount == 0) {
      System.out.printf("%s: Nothing to update\n", getClass().getSimpleName());
      return 0;
    }

    System.out.printf("%s: Found new %,d update%s\n", getClass().getSimpleName(),
            newFileCount, newFileCount > 1 ? "s" : "");

    Map<File, Boolean> updateResults = new HashMap<File, Boolean>();

    for (File newFile : files) {
      File currentFile = new File(newFile.getAbsolutePath().replaceFirst("(?i)_[0-9a-f]{16}$", ""));
      try {
        currentFile.delete();
        try { Thread.sleep(500); }
        catch (InterruptedException ie) {}
        updateResults.put(newFile, newFile.renameTo(currentFile));
      } catch (Exception ex) {
        updateResults.put(newFile, false);
      }
    }//for

    boolean hasError = false;
    StringBuffer msg = new StringBuffer(String.format(
            "Found new %,d update%s.\nUpdate results:\n\n", newFileCount, newFileCount > 1 ? "s" : ""));
    for (File file : updateResults.keySet()) {
      msg.append(String.format(" - %s: %s\n",
              file.getAbsolutePath().replaceFirst(String.format("(?i)%s", Pattern.quote(rootPath.getAbsolutePath())), ""),
              updateResults.get(file)));
      if (!hasError && !updateResults.get(file))
        hasError = true;
    }
    MessageBox.showInfoMsg(null, null, msg);

    return hasError ? 1 : 0;
  }

  @Override
  public int launch() {
    if (Debug) {
      System.out.printf("%s: launch()  :-)\n", getClass().getSimpleName());
    }

    String errMsg;

    File file = new File(String.format("%s/mail-gate.jar", rootPath.getAbsolutePath()));
    if (!file.isFile()) {
      errMsg = String.format("File \"%s\" does not exist!", file.getAbsolutePath());
      System.err.println(errMsg);
      MessageBox.showErrMsg(null, null, errMsg);
      return 1;
    }

    ProcessBuilder pb = new ProcessBuilder(new String[] {
      "java", "-jar", file.getAbsolutePath(),
      String.format("%s=%s", Lib.ArgNanoTime, Long.toString(System.nanoTime(), Character.MAX_RADIX))});
    try {
      pb.start();
      return 0;
    } catch (Exception ex) {
      errMsg = String.format("Failed to execute \"%s\":\n%s", file.getAbsolutePath(), ex);
      System.err.println(errMsg);
      MessageBox.showErrMsg(null, null, errMsg);
      return 1;
    }
  }
}
